package com.bl.student.service.biz.record.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.utils.ListUtils;
import com.bl.student.common.utils.UUIDUtils;
import com.bl.student.dao.model.*;
import com.bl.student.dao.repository.RecordRepository;
import com.bl.student.dao.repository.ShareRepository;
import com.bl.student.dao.repository.UserRepository;
import com.bl.student.service.biz.record.RecordService;
import com.bl.student.service.vo.DelBody;
import com.bl.student.service.vo.DelListBody;
import com.bl.student.service.vo.record.*;
import com.bl.student.service.vo.roaste.AbstractModel;
import com.bl.student.service.vo.roaste.CloudShare;
import com.bl.student.service.vo.user.UserInfoModifyVo;
import com.santoker.roastassistant.share.SharedData;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liangweikang on 20/6/27.
 */
@Log4j2
@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    RecordRepository recordRepository;

    @Autowired
    ShareRepository shareRepository;

    @Autowired
    UserRepository userRepository;

    private static final int PORT = 49936;
    private static final String ADDRESS = "127.0.0.1";

    @Override
    public List<UserRecordEntity> getUserRecordEntityList(int recordId) {
        List<UserRecordEntity> userRecordEntities = recordRepository.findByUserIdOrderByWeight(recordId);
        return userRecordEntities;
    }

    @Override
    public List<UserRecordEntity> getUserRecordEntityListByTitle(String title, int type) {
        List<UserRecordEntity> userRecordEntities = new ArrayList<>();
        if (type == 0) {
            userRecordEntities = recordRepository.findByTitleLikeAndShare("%"+title+ "%", 0);
        } else if (type == 1) {
            userRecordEntities = recordRepository.findByTitleLikeAndShare("%"+title+ "%", 1);
        } else {
            userRecordEntities = recordRepository.findByTitleLikeAndShareAndSelected("%"+title+ "%", 1, 1);
        }
        return userRecordEntities;
    }

    @Override
    public List<UserRecordEntity> getAllRecord() {
        Pageable pageable = new PageRequest(0, 500);
        Page<UserRecordEntity> recommendEntities  = recordRepository.findByOrderByCreateTime(pageable);
        return recommendEntities.getContent();
    }

    @Override
    public List<UserRecordTrainVo> getAllTrainRecord(String type) {

        List<UserRecordEntity> userRecordEntities  =  new ArrayList<>();
        if("Q".equals(type)) {
            List<UserRecordEntity> userRecordEntities1  =  new ArrayList<>();
            userRecordEntities = recordRepository.findByTrainAndTypeLike(1, "%"+"Q serious"+ "%" );
            userRecordEntities1 = recordRepository.findByTrainAndTypeLike(1, "%"+"Q 系列"+ "%" );
            userRecordEntities.addAll(userRecordEntities1);
        } else if("R".equals(type)){
            List<UserRecordEntity> userRecordEntities1  =  new ArrayList<>();
            userRecordEntities = recordRepository.findByTrainAndTypeLike(1, "%"+"R serious"+ "%" );
            userRecordEntities1 = recordRepository.findByTrainAndTypeLike(1, "%"+"R 系列"+ "%" );
            userRecordEntities.addAll(userRecordEntities1);
        }


        List<UserRecordTrainVo> userRecordTrainVoList  = new ArrayList<>();

        for (UserRecordEntity userRecordEntity : userRecordEntities) {
            UserRecordTrainVo userRecordTrainVo= new UserRecordTrainVo();

            userRecordTrainVo.setId(userRecordEntity.getId());
            userRecordTrainVo.setRecordId(userRecordEntity.getRecordId());
            userRecordTrainVo.setCreateTime(userRecordEntity.getCreateTime());
            userRecordTrainVo.setUserId(userRecordEntity.getUserId());
            userRecordTrainVo.setUserRecordId(userRecordEntity.getUserRecordId());
            userRecordTrainVo.setWeight(userRecordEntity.getWeight());
            userRecordTrainVo.setSelected(userRecordEntity.getSelected());
            userRecordTrainVo.setTitle(userRecordEntity.getTitle());
            userRecordTrainVo.setType(userRecordEntity.getType());
            userRecordTrainVo.setTrain(userRecordEntity.getTrain());
            userRecordTrainVo.setShare(userRecordEntity.getShare());

            UserEntity userEnty = userRepository.findOne(userRecordEntity.getUserId());
            userRecordTrainVo.setUserName(userEnty.getNickname());

            userRecordTrainVoList.add(userRecordTrainVo);
        }
        return userRecordTrainVoList;
    }

    @Override
    public void add(RecordAddVo addVo) {
        List<UserRecordEntity> userRecordEntityList = recordRepository.findByUserIdAndUserRecordId(addVo.getUserId(), addVo.getUserRecordId());
        if (userRecordEntityList != null && userRecordEntityList.size() > 0) {
            return;
        }
        UserRecordEntity userRecordEntity = new UserRecordEntity();
        userRecordEntity.setId(UUIDUtils.getUUID());
        userRecordEntity.setRecordId(addVo.getRecordId());
        userRecordEntity.setCreateTime(addVo.getCreateTime());
        userRecordEntity.setUserId(addVo.getUserId());
        userRecordEntity.setUserRecordId(addVo.getUserRecordId());
        userRecordEntity.setWeight(addVo.getWeight());
        userRecordEntity.setTitle(addVo.getRecordTitle());
        userRecordEntity.setType(addVo.getRecordType());
        recordRepository.save(userRecordEntity);
    }

    @Transactional
    @Override
    public void del(DelBody delBody) {
        recordRepository.deleteByUserIdAndUserRecordId(delBody.getUserId(), delBody.getId());
    }


    @Transactional
    @Override
    public void delAll(DelBody delBody) {
        recordRepository.deleteByUserId(delBody.getUserId());
    }

    @Transactional
    @Override
    public void delShare(DelBody delBody) {

        List<UserRecordEntity> userRecordEntities = recordRepository.findByUserIdAndUserRecordId(delBody.getUserId(), delBody.getId());

        if (userRecordEntities != null && userRecordEntities.size() > 0) {
            UserRecordEntity userRecordEntity = ListUtils.getFirst(userRecordEntities);
            userRecordEntity.setShare(0);
            userRecordEntity.setSelected(0);
            recordRepository.save(userRecordEntity);
        }
//        shareRepository.deleteByUserIdAndUserRecordId(delBody.getUserId(), delBody.getId());
    }

    @Override
    public void addShare(ShareAddVo addVo) {

        List<UserRecordEntity> userRecordEntities = recordRepository.findByUserIdAndUserRecordId(addVo.getUserId(), addVo.getUserRecordId());

        if (userRecordEntities != null && userRecordEntities.size() > 0) {
            UserRecordEntity userRecordEntity = ListUtils.getFirst(userRecordEntities);
            userRecordEntity.setShare(1);
            recordRepository.save(userRecordEntity);
        }

//        List<UserShareEntity> userShareEntityList = shareRepository.findByUserIdAndUserRecordId(addVo.getUserId(), addVo.getUserRecordId());
//        if (userShareEntityList != null && userShareEntityList.size() > 0) {
//            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "");
//        }
//        UserShareEntity userShareEntity = new UserShareEntity();
//        userShareEntity.setId(UUIDUtils.getUUID());
//        userShareEntity.setUserId(addVo.getUserId());
//        userShareEntity.setRecordId(addVo.getRecordId());
//        userShareEntity.setCreateTime(addVo.getCreateTime());
//        userShareEntity.setUserRecordId(addVo.getUserRecordId());
//        userShareEntity.setUserName(addVo.getUserName());
//        userShareEntity.setSelected(0);
//        userShareEntity.setTitle(addVo.getRecordTitle());
//        userShareEntity.setType(addVo.getRecordType());
//        shareRepository.save(userShareEntity);
    }

    @Override
    public void setIsSelect(ShareAddVo selectedVo) {

        List<UserRecordEntity> userRecordEntities = recordRepository.findByUserIdAndUserRecordIdAndShare(selectedVo.getUserId(), selectedVo.getUserRecordId(), 1);

        if (userRecordEntities != null && userRecordEntities.size() > 0) {
            UserRecordEntity userRecordEntity = ListUtils.getFirst(userRecordEntities);
            if (userRecordEntity.getSelected() == 0) {
                userRecordEntity.setSelected(1);
            } else {
                userRecordEntity.setSelected(0);
            }

            recordRepository.save(userRecordEntity);
        }

//        UserShareEntity userShareEntity = shareRepository.findOne(selectedVo.getRecordId());
//        userShareEntity.setSelected(selectedVo.getSelected());
//        shareRepository.save(userShareEntity);
    }

    @Override
    public void setIsTrain(RecordTrainVo recordTrainVo) {
        UserRecordEntity userRecordEntity = recordRepository.findOne(recordTrainVo.getId());
        if (userRecordEntity.getTrain() == 0) {
            userRecordEntity.setTrain(1);
        } else {
            userRecordEntity.setTrain(0);
        }
        recordRepository.save(userRecordEntity);
    }

    @Transactional
    @Override
    public void delTrainList(DelListBody idList) {
        for(String id: idList.getList()) {
            UserRecordEntity userRecordEntity = recordRepository.findOne(Integer.parseInt(id));
            if (userRecordEntity.getTrain() == 0) {
                userRecordEntity.setTrain(1);
            } else {
                userRecordEntity.setTrain(0);
            }
            recordRepository.save(userRecordEntity);
        }
    }

    @Override
    public void updateUserRcord(RecordModVo recordModVo) {
        List<UserRecordEntity> userRecordEntityList = recordRepository.findByUserRecordId(recordModVo.getUserRecordId());
        if (userRecordEntityList != null && userRecordEntityList.size() > 0) {
            UserRecordEntity userRecordEntity = ListUtils.getFirst(userRecordEntityList);
            userRecordEntity.setType(recordModVo.getRecordType());
            userRecordEntity.setTitle(recordModVo.getRecordTitle());
            recordRepository.save(userRecordEntity);
        }
    }

    @Override
    public void updateUserInfo(UserInfoModifyVo userInfoModifyVo) {
        UserEntity userEntity = userRepository.findOne(userInfoModifyVo.getId());
        userEntity.setNickname(userInfoModifyVo.getNickname());
        userEntity.setMobile(userInfoModifyVo.getMobile());
        userRepository.save(userEntity);
    }


    @Override
    public List<UserRecordEntity> getShareList(int userId) {
        List<UserRecordEntity> userRecordEntities = recordRepository.findByUserIdAndShare(userId, 1);
//        List<UserShareEntity> userShareEntityList = shareRepository.findByUserId(userId);
        return userRecordEntities;
    }

    @Override
    public List<UserVo> getUserNameList() {
        List<UserVo> userVoList = new ArrayList<>();
        List<UserRecordEntity> userRecordEntities = recordRepository.findGroupByUserId();
        for (UserRecordEntity userRecordEntity : userRecordEntities) {
            UserVo userVo = new UserVo();
            userVo.setUserId(userRecordEntity.getUserId());
            UserEntity userEntity = userRepository.findOne(userRecordEntity.getUserId());
            userVo.setUserName(userEntity.getNickname());
            userVo.setUserRecordId(userRecordEntity.getUserRecordId());
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public List<UserVo> getAllUser() {
        List<UserVo> userVoList = new ArrayList<>();
        List<UserEntity> userEntities = userRepository.findAll();
        for (UserEntity userEntity : userEntities) {
            UserVo userVo = new UserVo();
            userVo.setUserId(userEntity.getId());
            userVo.setUserName(userEntity.getNickname());
            userVo.setMobile(userEntity.getMobile());
            userVo.setCreateTime(userEntity.getCreateTime());
            userVo.setLocked(userEntity.getLocked());
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public List<UserVo> searchUserByName(String userName) {
        List<UserVo> userVoList = new ArrayList<>();
        List<UserEntity> userEntities = userRepository.findByNicknameLike("%"+userName+ "%" );
        for (UserEntity userEntity : userEntities) {
            UserVo userVo = new UserVo();
            userVo.setUserId(userEntity.getId());
            userVo.setUserName(userEntity.getNickname());
            userVo.setMobile(userEntity.getMobile());
            userVo.setCreateTime(userEntity.getCreateTime());
            userVo.setLocked(userEntity.getLocked());
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public List<UserVo> searchUserByMobile(String mobile) {
        List<UserVo> userVoList = new ArrayList<>();
        List<UserEntity> userEntities = userRepository.findByMobileLike( "%"+mobile+ "%" );
        for (UserEntity userEntity : userEntities) {
            UserVo userVo = new UserVo();
            userVo.setUserId(userEntity.getId());
            userVo.setUserName(userEntity.getNickname());
            userVo.setMobile(userEntity.getMobile());
            userVo.setCreateTime(userEntity.getCreateTime());
            userVo.setLocked(userEntity.getLocked());
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public List<UserVo> getUserNameListSelect() {
        List<UserVo> userVoList = new ArrayList<>();

        List<UserRecordEntity> userRecordEntities = recordRepository.findGroupByUserIdSelect();
        for (UserRecordEntity userRecordEntity : userRecordEntities) {
            UserVo userVo = new UserVo();
            userVo.setUserId(userRecordEntity.getUserId());
            UserEntity userEntity = userRepository.findOne(userRecordEntity.getUserId());
            userVo.setUserName(userEntity.getNickname());
            userVo.setUserRecordId(userRecordEntity.getUserRecordId());
            userVoList.add(userVo);
        }
        return userVoList;
    }

    @Override
    public SharedData getSharedData(String recordId) {
        CloudShare share = new CloudShare(ADDRESS, PORT);
        SharedData shareData = null;

        String errMsg = null;
        try {
            byte[] data = share.get(recordId);

            shareData = AbstractModel.create(data, SharedData.class);
        } catch (Exception e) {
            throw new IllegalStateException("getSharedData error", e);
        }

        return shareData;
    }
}
